/*
 * Created on Apr 11, 2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.vectrics.common.pagelist;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.vectrics.VectricsException;
import java.util.ArrayList;

public abstract class MemoryKeysPageList extends PageList {
	static private Log log = LogFactory.getLog(MemoryKeysPageList.class); 

	private List keys = null;
	private boolean reverse = false;

	/**
	 * 
	 */
	public MemoryKeysPageList() {
		super();
	}
	
	public int getTotalElementCount() {
		return(getKeys().size());
	}
	

	abstract public Object findElementForKey(Object key) throws VectricsException;
	
	/**
	 * @return Returns the keys.
	 */
	public List getKeys() {
		return keys;
	}

	/**
	 * @param keys The keys to set.
	 */
	public void setKeys(List keys) {
		this.keys = keys;
	}
	
	public List getElements(int start, int end) {
		log.debug("getElements() called");
		ArrayList elements = new ArrayList();
		try {
			log.debug("getElements() - got list");
			int size = this.getKeys().size();
			log.debug("getElements() - got size");
			int startIndex = start;
			int endIndex = end;
			if (this.getReverse()) {
				endIndex = size - (start + 1);
				startIndex = size - (end + 1); 
				if (endIndex < 0) {
					log.error("getElements() was passed an invalid end index: " 
							+ end + " Size = " + size);
					log.debug("getElements() was passed an invalid endIndex: " 
							+ endIndex + " Size = " + size);
					endIndex = 0; 
				}
				if (startIndex < 0) {
					log.error("getElements() was passed an invalid start index: " + start 
							+ " Size = " + size);
				}
			}
			
			for (int i = startIndex; i <= endIndex; i++) {
				Object id = (Object)getKeys().get(i);
				elements.add(findElementForKey(id));
			}
			if (log.isDebugEnabled()) {
				log.debug("getElements() - startIndex = " + startIndex);
				log.debug("getElements() - endIndex = " + startIndex);
				log.debug("getElements() - done, count = " + elements.size());
			}
		}
		catch (Exception de) {
			log.error("getElements() - Exception", de);
		}
		return(elements);	
	}
	
	
	
	/**
	 * @return Returns the reverse.
	 */
	public boolean getReverse() {
		return reverse;
	}

	/**
	 * @param reverse The reverse to set.
	 */
	public void setReverse(boolean reverse) {
		this.reverse = reverse;
	}

}
